const cosmos_strgate = require("@cosmjs/stargate");
const { TimeoutPromise} = require('./common/lib');
const config = require('./config');
class Client {
    constructor(nodeUrl) {
        this.nodeUrl= nodeUrl;
        this.client = null;
        this.ms = config.netTimeout;
        this.logger = global.appLogger;
    }

    async getClient() {
        try{
            if(this.client){
                return this.client;
            }else{
                let reqPromise =  cosmos_strgate.StargateClient.connect(this.nodeUrl);
                const reqPromiseWithTimeout = new TimeoutPromise(reqPromise, this.ms);
                this.client = await reqPromiseWithTimeout;
            }
        }catch (e) {
            this.logger.error('client connect', e);
            throw e;
        }
    }

    async getBlock(blockNumber) {
        try{
            let client = await this.getClient();
            let reqPromise =  client.getBlock(blockNumber);
            let reqPromiseWithTimeout = new TimeoutPromise(reqPromise,this.ms);
            let block = await reqPromiseWithTimeout;
            return block;
        }catch (e){
            this.logger.error('client getBlock, e: ', e);
            throw e;
        }

    }

}

module.exports = Client;
